<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="位置" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="时间">
             <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:data:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:data:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:data:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:data:export']"
        >导出</el-button>
      </el-col>

       <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="printHTML"
        >打印</el-button>
      </el-col>
    </el-row>

    <el-table id='data-table' v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="dataId" />
      <el-table-column label="位置" align="center" prop="address" />
      <el-table-column label="状态" align="center" prop="state" />
      <el-table-column label="纬度" align="center" prop="lat" />
      <el-table-column label="经度" align="center" prop="lng" />
      <el-table-column label="首要污染物" align="center" prop="wuran" />
      <el-table-column label="污染级别" align="center" prop="jibie" />
      <el-table-column label="AQI" align="center" prop="aqi" />
      <el-table-column label="PM2.5" align="center" prop="pm25" />
      <el-table-column label="PM10" align="center" prop="pm10" />
      <el-table-column label="TSP" align="center" prop="tsp" />
      <el-table-column label="噪声" align="center" prop="zaosheng" />
      <el-table-column label="温度" align="center" prop="wendu" />
      <el-table-column label="湿度" align="center" prop="shidu" />
      <el-table-column label="风速" align="center" prop="fengsu" />
      <el-table-column label="风向" align="center" prop="fengxiang" />
      <el-table-column label="气压" align="center" prop="qiya" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:data:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:data:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监测数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="监测点">
              <el-select v-model="form.addressId"  placeholder="请选择">
                <el-option
                  v-for="item in addressOptions"
                  :key="item.addressId"
                  :label="item.addName"
                  :value="item.addressId"
                ></el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="首要污染物" prop="wuran">
          <el-input v-model="form.wuran" placeholder="请输入首要污染物" />
        </el-form-item>
        <el-form-item label="污染级别" prop="jibie">
          <el-input v-model="form.jibie" placeholder="请输入污染级别" />
        </el-form-item>
        <el-form-item label="AQI" prop="aqi">
          <el-input v-model="form.aqi" placeholder="请输入AQI" />
        </el-form-item>
        <el-form-item label="PM2.5" prop="pm25">
          <el-input v-model="form.pm25" placeholder="请输入PM2.5" />
        </el-form-item>
        <el-form-item label="PM10" prop="pm10">
          <el-input v-model="form.pm10" placeholder="请输入PM10" />
        </el-form-item>
        <el-form-item label="TSP" prop="tsp">
          <el-input v-model="form.tsp" placeholder="请输入TSP" />
        </el-form-item>
        <el-form-item label="噪声" prop="zaosheng">
          <el-input v-model="form.zaosheng" placeholder="请输入噪声" />
        </el-form-item>
        <el-form-item label="温度" prop="wendu">
          <el-input v-model="form.wendu" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="湿度" prop="shidu">
          <el-input v-model="form.shidu" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="风速" prop="fengsu">
          <el-input v-model="form.fengsu" placeholder="请输入风速" />
        </el-form-item>
        <el-form-item label="风向" prop="fengxiang">
          <el-input v-model="form.fengxiang" placeholder="请输入风向" />
        </el-form-item>
        <el-form-item label="气压" prop="qiya">
          <el-input v-model="form.qiya" placeholder="请输入气压" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
function printHTML(id) {
    const html = document.querySelector('#' + id).innerHTML
    // 新建一个 DOM
    const div = document.createElement('div')
    const printDOMID = 'printDOMElement'
    div.id = printDOMID
    div.innerHTML = html

    // 提取第一个表格的内容 即表头
    const ths = div.querySelectorAll('.el-table__header-wrapper th')
    const ThsTextArry = []
    for (let i = 0, len = ths.length; i < len; i++) {
        if (ths[i].innerText !== '') ThsTextArry.push(ths[i].innerText)
    }

    // 删除多余的表头
    div.querySelector('.hidden-columns').remove()
    // 第一个表格的内容提取出来后已经没用了 删掉
    div.querySelector('.el-table__header-wrapper').remove()

    // 将第一个表格的内容插入到第二个表格
    let newHTML = '<tr>'
    for (let i = 0, len = ThsTextArry.length; i < len; i++) {
        newHTML += '<td style="text-align: center; font-weight: bold">' + ThsTextArry[i] + '</td>'
    }

    newHTML += '</tr>'
    div.querySelector('.el-table__body-wrapper table').insertAdjacentHTML('afterbegin', newHTML)
    // 将新的 DIV 添加到页面 打印后再删掉
    document.querySelector('body').appendChild(div)
    
    printJS({
        printable: printDOMID,
        type: 'html',
        scanStyles: false,
        style: 'table { border-collapse: collapse }' // 表格样式
    })

    div.remove()
}
// 这个函数 网上  随处可见，我也是应用了别人的。
 function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};
 
function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}
import { listData, getData, delData, addData, updateData, exportData } from "@/api/system/data";
import { listAddress  } from "@/api/system/address";
import printJS from 'print-js'
export default {
  name: "Data",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      pickerOptions: {
          shortcuts: [{
            text: '最近半天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 12);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 );
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 监测数据表格数据
      dataList: [],
      addressOptions:[],
      // 弹出层标题
      title: "",
      dateRange: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        addressId:undefined,
        address: undefined,
        lat: undefined,
        lng: undefined,
        wuran: undefined,
        jibie: undefined,
        aqi: undefined,
        pm25: undefined,
        pm10: undefined,
        tsp: undefined,
        zaosheng: undefined,
        wendu: undefined,
        shidu: undefined,
        fengsu: undefined,
        fengxiang: undefined,
        qiya: undefined,
        createTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    listAddress().then(res=>{
      this.addressOptions = res.rows
    })
  },
  methods: {
    /** 查询监测数据列表 */
    getList() {
      this.loading = true;
     if (null != this.dateRange && '' != this.dateRange) {
	 this.dateRange[0] = formatDate(this.dateRange[0], 'yyyy-MM-dd hh:mm:ss')
		 this.dateRange[1] =  formatDate(this.dateRange[1], 'yyyy-MM-dd hh:mm:ss')
	}
      listData(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    printHTML(id) {
      var id = "data-table" 
    const html = document.querySelector('#' + id).innerHTML
    // 新建一个 DOM
    const div = document.createElement('div')
    const printDOMID = 'printDOMElement'
    div.id = printDOMID
    div.innerHTML = html

    // 提取第一个表格的内容 即表头
    const ths = div.querySelectorAll('.el-table__header-wrapper th')
    const ThsTextArry = []
    for (let i = 0, len = ths.length; i < len; i++) {
        if (ths[i].innerText !== '') ThsTextArry.push(ths[i].innerText)
    }

    // 删除多余的表头
    div.querySelector('.hidden-columns').remove()
    // 第一个表格的内容提取出来后已经没用了 删掉
    div.querySelector('.el-table__header-wrapper').remove()

    // 将第一个表格的内容插入到第二个表格
    let newHTML = '<tr>'
    for (let i = 0, len = ThsTextArry.length; i < len; i++) {
        newHTML += '<td style="text-align: center; font-weight: bold">' + ThsTextArry[i] + '</td>'
    }

    newHTML += '</tr>'
    div.querySelector('.el-table__body-wrapper table').insertAdjacentHTML('afterbegin', newHTML)
    // 将新的 DIV 添加到页面 打印后再删掉
    document.querySelector('body').appendChild(div)
    
    printJS({
        printable: printDOMID,
        type: 'html',
        scanStyles: false,
        style: 'table { border-collapse: collapse }' // 表格样式
    })

    div.remove()
},
    // 表单重置
    reset() {
      this.form = {
        dataId: undefined,
        address: undefined,
        lat: undefined,
        lng: undefined,
        wuran: undefined,
        jibie: undefined,
        aqi: undefined,
        pm25: undefined,
        pm10: undefined,
        tsp: undefined,
        zaosheng: undefined,
        wendu: undefined,
        shidu: undefined,
        fengsu: undefined,
        fengxiang: undefined,
        qiya: undefined,
        createBy: undefined,
        createTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监测数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dataId = row.dataId || this.ids
      getData(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改监测数据";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.addressId
      for(let i in this.addressOptions){
        if( this.addressOptions[i].addressId == this.form.addressId){
          this.form.address = this.addressOptions[i].addName
          this.form.lng =  this.addressOptions[i].lng
          this.form.lat =  this.addressOptions[i].lat
        }
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataId != undefined) {
            updateData(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addData(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dataIds = row.dataId || this.ids;
      this.$confirm('是否确认删除监测数据编号为"' + dataIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delData(dataIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有监测数据数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportData(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>